package com.dropdb.demo.service.impl;

import com.dropdb.demo.bean.*;
import com.dropdb.demo.bean.System;
import com.dropdb.demo.bean.bo.*;
import com.dropdb.demo.bean.vo.BaseRespVO;
import com.dropdb.demo.mapper.*;
import com.dropdb.demo.service.PromotionService;
import com.dropdb.demo.service.WxCartService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author:tanxin Desc: 购物车serviceImpl
 * @date:2020/6/30 12:31
 */
@Service
public class WxCartServiceImpl implements WxCartService {

    @Resource
    CartMapper cartMapper;
    @Resource
    AddressMapper addressMapper;
    @Resource
    CouponMapper couponMapper;
    @Resource
    GoodsMapper goodsMapper;
    @Resource
    GoodsProductMapper goodsProductMapper;
    @Resource
    SystemMapper systemMapper;
    @Resource
    PromotionService promotionService;
    ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 添加商品至购物车
     * @param userId 用户id
     */
    @SneakyThrows
    @Override
    public int add2Cart(Integer userId, AddCartBO addCartBO) {
        //判断商品是否可以购买--是否在售
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andIdEqualTo(addCartBO.getGoodsId());
        //按productId来查询对应商品的规格
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        goodsProductExample.createCriteria().andIdEqualTo(addCartBO.getProductId());
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);
        for (Goods good : goods) {
            if (!good.getIsOnSale()) {
                return 400;
            }
        }
        //判断购物车 是否存在此规格产品，若有就合并
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andGoodsIdEqualTo(addCartBO.getGoodsId()).andProductIdEqualTo(addCartBO.getProductId()).
                andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        //存在该规格 更新number即可
        int num = 0;
        if (!carts.isEmpty()){
            for (Cart cart : carts) {
                num = cart.getNumber().intValue();
                num += addCartBO.getNumber();
                cart.setNumber((short) num);
                //更新数据
                cartMapper.updateByPrimaryKey(cart);
            }
        }else{
            String goodsName = null;
            BigDecimal price = new BigDecimal(0);
            String spec = null;
            String picUrl = null;
            for (Goods good : goods) {
                price = new BigDecimal(good.getRetailPrice());
                goodsName = good.getName();
                picUrl = good.getPicUrl();
            }
            for (GoodsProduct goodsProduct : goodsProducts) {
                //获取该商品的规格
               spec = objectMapper.writeValueAsString(goodsProduct.getSpecifications());
            }
            //添加至购物车的数据
            Cart cart = new Cart();
            cart.setNumber(addCartBO.getNumber());
            cart.setUserId(userId);
            cart.setGoodsId(addCartBO.getGoodsId());
            cart.setGoodsSn(Integer.toString(addCartBO.getGoodsId()));
            cart.setGoodsName(goodsName);
            cart.setProductId(addCartBO.getProductId());
            cart.setPrice(price);
            cart.setSpecifications(spec);
            cart.setChecked(true);
            cart.setPicUrl(picUrl);
            cart.setAddTime(new Date());
            cart.setUpdateTime(new Date());
            cart.setDeleted(false);
            cartMapper.insert(cart);
        }
        return num;
    }

    /**
     * 立即购买
     * 和add方法的区别：
     * 1、如果购物车已存在该商品，前者的是商品数量的添加，这里是商品数量的覆盖
     * 2、返回值：add 返回的是当前购物车商品数量，这里返回的是该商品在购物车的cartId
     * @param userId    用户id
     * @param addCartBO {"goodsId":xxx,"number":xx,"productId":xxx}
     * @return 返回的是该商品在购物车的cartId
     */
    @SneakyThrows
    @Override
    public BaseRespVO fastAdd(Integer userId, AddCartBO addCartBO) {
        //判断商品是否可以购买--是否在售
        GoodsExample goodsExample = new GoodsExample();
        goodsExample.createCriteria().andIdEqualTo(addCartBO.getGoodsId());
        //按productId来查询对应商品的规格
        GoodsProductExample goodsProductExample = new GoodsProductExample();
        goodsProductExample.createCriteria().andIdEqualTo(addCartBO.getProductId());
        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
        List<Goods> goods = goodsMapper.selectByExample(goodsExample);
        for (Goods good : goods) {
            if (!good.getIsOnSale()) {
                return BaseRespVO.error(400,"商品下架了！");
            }
        }
        //判断购物车 是否存在此规格产品，若有就覆盖数目
        CartExample cartExample = new CartExample();
        cartExample.createCriteria().andUserIdEqualTo(userId).andGoodsIdEqualTo(addCartBO.getGoodsId()).andProductIdEqualTo(addCartBO.getProductId()).
                andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        //存在该规格 覆盖number
        int cartId = 0;
        if (!carts.isEmpty()){
            for (Cart cart : carts) {
                cart.setNumber(addCartBO.getNumber());
                //获取返回的 cartId
                cartId = cart.getId();
                //更新数据
                cartMapper.updateByPrimaryKey(cart);
            }
        }else{//购物车无此规格商品
            String goodsName = null;
            BigDecimal price = new BigDecimal(0);
            String spec = null;
            String picUrl = null;
            for (Goods good : goods) {
                price = new BigDecimal(good.getRetailPrice());
                goodsName = good.getName();
                picUrl = good.getPicUrl();
            }
            for (GoodsProduct goodsProduct : goodsProducts) {
                //获取该商品的规格
                spec = objectMapper.writeValueAsString(goodsProduct.getSpecifications());
            }
            //添加至购物车的数据
            Cart cart = new Cart();
            cart.setNumber(addCartBO.getNumber());
            cart.setUserId(userId);
            cart.setGoodsId(addCartBO.getGoodsId());
            cart.setGoodsSn(Integer.toString(addCartBO.getGoodsId()));
            cart.setGoodsName(goodsName);
            cart.setProductId(addCartBO.getProductId());
            cart.setPrice(price);
            cart.setSpecifications(spec);
            cart.setChecked(true);
            cart.setPicUrl(picUrl);
            cart.setAddTime(new Date());
            cart.setUpdateTime(new Date());
            cart.setDeleted(false);
            cartMapper.insert(cart);
            //获得自增长的cartId
            cartId = cart.getId();
        }
        return BaseRespVO.ok(cartId);
    }

    /**
     * @param userId 当前登录的用户id
     * @return 返回购物车中商品列表
     */
    @Override
    public CartDataBO queryCartIndex(Integer userId) {
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        //待封装的购物车数据
        CartDataBO cartDataBO = new CartDataBO();
        criteria.andUserIdEqualTo(userId).andDeletedEqualTo(false);
        //购物车商品总数
        Integer goodCount = 0;
        //购物车商品总价格
        //BigDecimal goodsAmount = new BigDecimal(0.00);
        BigDecimal goodsAmount = BigDecimal.valueOf(0.00);
        //已选商品总数
        Integer checkedGoodsCount = 0;
        //已选商品总价格
        BigDecimal checkedGoodsAmount =BigDecimal.valueOf(0.00);
        //查询对应购物车list
        List<Cart> cartList = cartMapper.selectByExample(cartExample);

        for (Cart cart : cartList) {
            if (!cart.getDeleted()) {
            goodCount += cart.getNumber();
            goodsAmount = goodsAmount.add(cart.getPrice());
                if (cart.getChecked()){
                    //已经选择的商品价格 和 数目
                    checkedGoodsCount += cart.getNumber();
                    checkedGoodsAmount = checkedGoodsAmount.add(cart.getPrice().multiply(BigDecimal.valueOf(cart.getNumber())));
                }
            }
        }
        CartTotalBO cartTotal = new CartTotalBO(goodCount,checkedGoodsCount,goodsAmount,checkedGoodsAmount);
        cartDataBO.setCartTotal(cartTotal);
        cartDataBO.setCartList(cartList);
        return cartDataBO;
    }

   /**
     * 更新商品的checked状态
     * @param userId 用户id
     * @return 返回购物车数据*/
    @Override
    public CartDataBO updateCartChecked(Integer userId, ProductIdsBO productIds) {
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        //先更新checked状态，再进行数据封装
        //先查询userid 的用户
        criteria.andUserIdEqualTo(userId).andDeletedEqualTo(false);
        //待封装的购物车数据
        CartDataBO cartDataBO = new CartDataBO();
        //购物车商品总数
        Integer goodCount = 0;
        //购物车商品总价格
        BigDecimal goodsAmount = BigDecimal.valueOf(0.00);
        //已选商品总数
        Integer checkedGoodsCount = 0;
        //已选商品总价格
        BigDecimal checkedGoodsAmount = BigDecimal.valueOf(0.00);
        //查询对应购物车list
        List<Cart> cartList = cartMapper.selectByExample(cartExample);
        //更新购物车商品的checked状态
        for (Cart cart : cartList) {
            for (Integer productId : productIds.getProductIds()){
                if (cart.getProductId().equals(productId) && productIds.getIsChecked() == 1){
                        cart.setChecked(true);
                }
            }
            for (Integer productId : productIds.getProductIds()){
                if (cart.getProductId().equals(productId) && productIds.getIsChecked() == 0){
                        cart.setChecked(false);
                }
            }
            //更新数据库
            cartMapper.updateByPrimaryKey(cart);
            //计算购物车中所有商品总数
            goodCount += cart.getNumber();
            goodsAmount = goodsAmount.add(cart.getPrice());
            if (cart.getChecked()){
                //已经选择的商品价格 和 数目
                checkedGoodsCount += cart.getNumber();
                checkedGoodsAmount = checkedGoodsAmount.add(cart.getPrice().multiply(BigDecimal.valueOf(cart.getNumber())));
            }
        }
        CartTotalBO cartTotal = new CartTotalBO(goodCount,checkedGoodsCount,goodsAmount,checkedGoodsAmount);
        cartDataBO.setCartTotal(cartTotal);
        cartDataBO.setCartList(cartList);
        return cartDataBO;
    }

    @Override
    public int queryCartGoodsCount(Integer userId) {
        CartExample cartExample = new CartExample();
        //购物车商品总数
        int goodsCount = 0;
        //查询对应购物车list
        List<Cart> cartList = cartMapper.selectByExample(cartExample);
        for (Cart cart : cartList) {
            if (!cart.getDeleted()) {
                goodsCount += cart.getNumber();
            }
        }
        return goodsCount;
    }

    @Override
    public void updateCart(Integer userId, CartUpdateBO cartUpdateBO) {
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);

        for (Cart cart : carts) {
            if (cart.getProductId().equals(cartUpdateBO.getProductId())){
                cart.setNumber(cartUpdateBO.getNumber());
            }
            //更新数据库
            cartMapper.updateByPrimaryKey(cart);
        }
    }

    @Override
    public CartDataBO deleteCartByProductId(Integer userId, CartDeleteBO cartDeleteBO) {
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        //待封装的购物车数据
        CartDataBO cartDataBO = new CartDataBO();
        //购物车商品总数
        Integer goodCount = 0;
        //购物车商品总价格
        BigDecimal goodsAmount = BigDecimal.valueOf(0.00);
        //已选商品总数
        Integer checkedGoodsCount = 0;
        //已选商品总价格
        BigDecimal checkedGoodsAmount = BigDecimal.valueOf(0.00);
        //用于存放物理删除后剩下的购物车list
        List<Cart> list = new ArrayList<>();
        for (Cart cart : carts) {
            for (Integer productId : cartDeleteBO.getProductIds()) {
                if (cart.getProductId().equals(productId)) {
                    cart.setDeleted(true);
                }
            }
            cartMapper.updateByPrimaryKey(cart);
            //如果没有被删除
            if (!cart.getDeleted()){
                list.add(cart);
            //计算购物车中所有商品总数
            goodCount += cart.getNumber();
            goodsAmount = goodsAmount.add(cart.getPrice());
                if (cart.getChecked()) {
                    //已经选择的商品价格 和 数目
                    checkedGoodsCount += cart.getNumber();
                    checkedGoodsAmount = checkedGoodsAmount.add(cart.getPrice().multiply(BigDecimal.valueOf(cart.getNumber())));
                }
            }
        }
        CartTotalBO cartTotal = new CartTotalBO(goodCount, checkedGoodsCount, goodsAmount, checkedGoodsAmount);
        cartDataBO.setCartTotal(cartTotal);
        cartDataBO.setCartList(list);
        return cartDataBO;
    }

    @Override
    public CheckOutDataBO checkout(Integer userId, Integer cartId, Integer addressId, Integer couponId, Integer grouponRulesId) {

        CheckOutDataBO checkOutDataBO = new CheckOutDataBO();
        checkOutDataBO.setAddressId(addressId);
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        //待封装的购物车数据
        CartDataBO cartDataBO = new CartDataBO();
        //购物车商品总数
        Integer goodCount = 0;
        //购物车商品总价格
        BigDecimal goodsAmount = BigDecimal.valueOf(0.00);
        //已选商品总数
        Integer checkedGoodsCount = 0;
        //已选商品总价格
        BigDecimal checkedGoodsAmount = BigDecimal.valueOf(0.00);
        //商品页立即购买时的价格
        BigDecimal fastAddPrice =  new BigDecimal(0);
        //已选的商品列表
        ArrayList<Cart> list = new ArrayList<>();
        //立即购买下单时的商品列表
        ArrayList<Cart> fastList = new ArrayList<>();

        for (Cart cart : carts) {
            //如果没有被删除
            if (!cart.getDeleted() && cart.getChecked()){
                list.add(cart);
                //已经选择的商品价格 和 数目
                checkedGoodsCount += cart.getNumber();
                checkedGoodsAmount = checkedGoodsAmount.add(cart.getPrice().multiply(BigDecimal.valueOf(cart.getNumber())));
            }
            //立即购买时商品的价格和下单列表
            if (cart.getId().equals(cartId)){
                fastAddPrice = cart.getPrice();
                BigDecimal x = new BigDecimal(cart.getNumber());
                fastAddPrice = x.multiply(fastAddPrice);
                fastList.add(cart);
            }
        }

        //根据满减规则 显示 可用消费券个数
        int len = promotionService.selectCouponList(userId, cartId).size();
        checkOutDataBO.setAvailableCouponLength(len);

        //优惠券满减（获取消费券满减额度）
        BigDecimal couponPrice = new BigDecimal(0);
        BigDecimal min = new BigDecimal(0);
        if (couponId != 0 && couponId != -1) {
            //优惠券使用最低额度
            min = couponMapper.selectByPrimaryKey(couponId).getMin();
            //优惠券面值
            couponPrice = couponMapper.selectByPrimaryKey(couponId).getDiscount();
        }
        checkOutDataBO.setCouponPrice(couponPrice);
        checkOutDataBO.setCouponId(couponId);
        //运费，从数据库获取
        BigDecimal freightPrice = new BigDecimal(0);
        //设置满减
        SystemExample systemExample1 = new SystemExample();
        systemExample1.createCriteria();
        List<System> systems = systemMapper.selectByExample(systemExample1);
        //获取运费满减额度，一般是88.00
        int freightMin = 0;
        //获取运费
        int hasFreight = 0;
        for (System system : systems) {
            if (system.getKeyName().equals("cskaoyan_mall_express_freight_min")){
                freightMin = Integer.parseInt(system.getKeyValue());
            }
            if (system.getKeyName().equals("cskaoyan_mall_express_freight_value")){
                hasFreight = Integer.parseInt(system.getKeyValue());
            }
        }

        //商品合计
        //购物车下单
        if (cartId == 0){
            checkOutDataBO.setGoodsTotalPrice(checkedGoodsAmount);
            if (checkedGoodsAmount.compareTo(BigDecimal.valueOf(freightMin)) < 0){
                //需要运费
                freightPrice = new BigDecimal(hasFreight);
            }
            if (checkedGoodsAmount.compareTo(min) < 0){
                //该优惠券不能使用
                checkOutDataBO.setCouponId(-1);
                couponPrice = new BigDecimal(0);
                checkOutDataBO.setCouponPrice(couponPrice);
            }
            checkOutDataBO.setFreightPrice(freightPrice);
            //实际价格 = 运费（满减） + 商品价格(已经checked的商品) + 优惠券满减
            BigDecimal actualPrice = new BigDecimal(0);
            actualPrice = actualPrice.add(checkedGoodsAmount).subtract(couponPrice).add(freightPrice);
            checkOutDataBO.setActualPrice(actualPrice);
            checkOutDataBO.setOrderTotalPrice(actualPrice);
            //订单选购的商品list
            checkOutDataBO.setCheckedGoodsList(list);

        }else{
            //商品页立即购买 下单
            if (fastAddPrice.compareTo(BigDecimal.valueOf(freightMin)) < 0){
                //需要运费
                freightPrice = new BigDecimal(hasFreight);
            }
            if (fastAddPrice.compareTo(min) < 0){
                //该优惠券不能使用
                checkOutDataBO.setCouponId(-1);
                couponPrice = new BigDecimal(0);
                checkOutDataBO.setCouponPrice(couponPrice);
            }
            checkOutDataBO.setFreightPrice(freightPrice);

            //实际价格 = 运费（满减） + 商品价格(已经checked的商品) + 优惠券满减
            BigDecimal actualPrice = new BigDecimal(0);
            actualPrice = actualPrice.add(fastAddPrice).subtract(couponPrice).add(freightPrice);
            checkOutDataBO.setActualPrice(actualPrice);
            checkOutDataBO.setGoodsTotalPrice(actualPrice);
            checkOutDataBO.setCheckedGoodsList(fastList);
        }
        //团购券id
        checkOutDataBO.setGrouponRulesId(0);
        //设置收货地址
        AddressExample addressExample = new AddressExample();
        addressExample.createCriteria().andUserIdEqualTo(userId).andIdEqualTo(addressId);
        List<Address> addresses = addressMapper.selectByExample(addressExample);
        //已选地址
        for (Address address : addresses) {
            if (address.getId().equals(addressId)) {
                checkOutDataBO.setCheckedAddress(address);
            }
        }
        return checkOutDataBO;
    }
}
